//
//  UICollectionView+wgPlaceholderView.m
//  WGTool
//
//  Created by czw on 2022/8/18.
//

#import "UICollectionView+wgPlaceholderView.h"
#import <objc/runtime.h>
#import "NSObject+wgSwizzle.h"

static NSString *const placeholderViewKey = @"WG_CollectionViewPlaceholderViewKey";

static NSString *const isLoadEndDataKey = @"WG_CollectionViewIsLoadEndDataKey";


@implementation UICollectionView (wgPlaceholderView)
+(void)load{
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken, ^{
        [self wg_swizzleInstanceSelector:@selector(reloadData) WithSwizzledSelector:@selector(wg_ReloadData)];
    });
}
-(void)wg_ReloadData{
    [self wg_DataEmpty];
    [self wg_ReloadData];
}

- (void)setPlaceholderView:(UIView *)placeholderView{
    objc_setAssociatedObject(self, (__bridge const void *)(placeholderViewKey), placeholderView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIView *)placeholderView{
    return  objc_getAssociatedObject(self, (__bridge const void *)(placeholderViewKey));
}

- (void)setIsLoadEndData:(BOOL)isLoadEndData{
    
    objc_setAssociatedObject(self, (__bridge const void *)(isLoadEndDataKey), [NSNumber numberWithBool:isLoadEndData], OBJC_ASSOCIATION_ASSIGN);
    
}


- (BOOL)isLoadEndData{
    return  ((NSNumber*)objc_getAssociatedObject(self, (__bridge const void *)(isLoadEndDataKey))).boolValue;
}

- (void)wg_DataEmpty{
    
    BOOL isEmpty = YES;
    id <UICollectionViewDataSource> ds = self.dataSource;
    NSInteger sections = 1;
    if ([ds respondsToSelector:@selector(numberOfSectionsInCollectionView:)]) {
        sections = [ds numberOfSectionsInCollectionView:self];
    }
    for (NSInteger i  = 0; i < sections; i++ ) {
        NSInteger rows  =  [ds collectionView:self numberOfItemsInSection:i];
        if (rows) {
            isEmpty = NO;
        }
    }
    
    if (isEmpty&&self.isLoadEndData) {
        [self.placeholderView removeFromSuperview];
        [self addSubview:self.placeholderView];
    }else{
        [self.placeholderView removeFromSuperview];
    }
}
@end
